package model

import (
	"fmt"
	"github.com/rs/zerolog/log"
	"shyxy-net/pkg/fiber"
	"time"
)

func (ms *Service) CheckIfModelExists(modelName string) (bool, error) {
	var result fiber.Result
	var err error
	toModelExistsPath := func(modelName string) string {
		return fmt.Sprintf("/models/%s/exists", modelName)
	}
	for i := 0; i < 3; i++ {
		err = ms.client.Get(toModelExistsPath(modelName), &result)
		if err == nil {
			break
		}
		log.Debug().Msgf("Attempt %d failed: %v", i+1, err)
		time.Sleep(100 * time.Millisecond)
	}

	if err != nil {
		return false, err
	}

	if result.Code != 0 {
		return false, fmt.Errorf("error msg:%s", result.Msg)
	}

	existsValue, exists := result.Data["exists"]
	if !exists {
		return false, fmt.Errorf("missing exists in data")
	}
	checkExists, ok := existsValue.(bool)
	if !ok {
		return false, fmt.Errorf("unexpected type for exists: %T", existsValue)
	}
	return checkExists, nil
}
